package com.ruoyi.web.core.config;


import net.bull.javamelody.MonitoringFilter;
import net.bull.javamelody.SessionListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class JavaMelodyConfig {
    @Value("${javamelody.enabled:false}")
    private boolean enabled;
    @Value("${javamelody.init-parameters.authorized-users:}")
    private String users;
    @Value("${javamelody.init-parameters.log:false}")
    private String   logEnabled;

    @Value("${javamelody.init-parameters.storage-directory:}")
    private String storageDirectory;
    /**
     * 配置javamelody监控
     * spring boot 会按照order值的大小，从小到大的顺序来依次过滤
     */
    @Bean
    @Order(Integer.MAX_VALUE-1)
    public FilterRegistrationBean<MonitoringFilter> monitoringFilter() {
        FilterRegistrationBean<MonitoringFilter>  registration = new FilterRegistrationBean<MonitoringFilter>();
        registration.setFilter(new MonitoringFilter());
        registration.addUrlPatterns("/*");
        registration.setName("monitoring");
        registration.setEnabled(enabled);
        Map<String, String> initParameters=new HashMap<String, String>();
        initParameters.put("authorized-users",users);
        initParameters.put("log",logEnabled);
        initParameters.put("storage-directory",storageDirectory);
        registration.setInitParameters(initParameters);
        return registration;
    }

    /**
     *  配置javamelody监听器sessionListener
     */
    @Bean
    public ServletListenerRegistrationBean<SessionListener> servletListenerRegistrationBean() {
        ServletListenerRegistrationBean<SessionListener> slrBean = new ServletListenerRegistrationBean<SessionListener>();
        slrBean.setListener(new SessionListener());
        return slrBean;
    }
}
